package com.wstuo.common.config.customfilter.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.customfilter.dao.IExpressionDAO;
import com.wstuo.common.config.customfilter.dao.IFilterDAO;
import com.wstuo.common.config.customfilter.dto.CustomExpressionDTO;
import com.wstuo.common.config.customfilter.dto.CustomFilterDTO;
import com.wstuo.common.config.customfilter.dto.CustomFilterQueryDTO;
import com.wstuo.common.config.customfilter.entity.CustomExpression;
import com.wstuo.common.config.customfilter.entity.CustomFilter;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryItemsDAO;
import com.wstuo.common.config.dictionary.entity.DataDictionaryItems;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;
/**
 * 过滤器Service实现类
 * @author Will
 *
 */
public class FilterService implements IFilterService {
	final static Logger LOGGER = Logger.getLogger(FilterService.class);
	@Autowired
	private IExpressionDAO expressionDAO;

	@Autowired
	private IFilterDAO filterDAO;

	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private IExpressionService expressionService;
	@Autowired
	private IDataDictionaryItemsDAO dataDictionaryItemDAO;
	/**
	 * 根据过滤器查询数据
	 */
	public PageDTO findPageByFilter(Long filterId, int start, int limit,
			String sidx, String sord) {
		return findPageByFilter(filterId, null,null, start, limit, sidx, sord);
	}
	/**
	 * 根据过滤器查询数据
	 */
	@SuppressWarnings("rawtypes")
    public List findByFilter(Long filterId, int start, int limit,
			String sidx, String sord) {
		return findByCustomFilter(filterId, null,null, start, limit, sidx, sord);
	}


	/**
	 * 根据类名获取表字段的信息
	 * 
	 * @param className
	 * @return Map
	 */
	@SuppressWarnings("rawtypes")
    @Transactional
	public Map getClassMetaDataByClassName(String className) {
		return filterDAO.getClassMetaDataByClassName(className);
	}

	/**
	 * 查询我的私有过滤器.
	 * 
	 * @param queryDTO
	 */
	@Transactional
	public List<CustomFilterDTO> findMyFilters(CustomFilterQueryDTO queryDTO) {

		List<CustomFilter> customFilters = filterDAO.findMyFilters(queryDTO.getUserName(), queryDTO.getFilterCategory());
		List<CustomFilterDTO> list = null;
		if (customFilters != null && customFilters.size() > 0) {
			list = new ArrayList<CustomFilterDTO>(customFilters.size());
			for (CustomFilter ft : customFilters) {
				CustomFilterDTO customFilterDTO = new CustomFilterDTO();
				customFilterDTO.setFilterId(ft.getFilterId());
				customFilterDTO.setFilterName(ft.getFilterName());
				customFilterDTO.setShare(ft.getShare());
				list.add(customFilterDTO);
			}
		}
		return list;
	}

	/**
	 * 去除LIST重复对象
	 * 
	 * @param list
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static List removeDuplicateWithOrder(List list) {
		Set set = new HashSet();
		List newList = new ArrayList();
		for (Iterator iter = list.iterator(); iter.hasNext();) {
			Object element = iter.next();
			if (set.add(element))
				newList.add(element);
		}
		return newList;
	}

	/**
	 * 根据用户名获取用户的过滤器
	 * 
	 * @param queryDTO
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public List<CustomFilterDTO> findFiltersByUserName(
			CustomFilterQueryDTO queryDTO) {
		List<CustomFilterDTO> list = new ArrayList<CustomFilterDTO>();
		// 获取用户的过滤器
		List<CustomFilter> customFilters = filterDAO.findFiltersByUser(
				queryDTO.getUserName(), queryDTO.getFilterCategory());
		customFilters = removeDuplicateWithOrder(customFilters);
		if (customFilters != null && customFilters.size() > 0) {
			for (int i = 0; i < customFilters.size(); i++) {
				CustomFilter customFilter = customFilters.get(i);
				CustomFilterDTO customFilterDTO = new CustomFilterDTO();
				CustomFilterDTO.entity2dto(customFilter, customFilterDTO);
				// 获取过滤器里的表达式
				List<CustomExpression> expressions = customFilter
						.getExpressions();
				List<CustomExpressionDTO> expressionDtos = new ArrayList<CustomExpressionDTO>();
				if (expressions != null && expressions.size() > 0) {
					// 将表达式放入DTO中
					for (int j = 0; j < expressions.size(); j++) {
						CustomExpression expression = expressions.get(j);
						CustomExpressionDTO expressionDTO = new CustomExpressionDTO();
						CustomExpressionDTO.entity2dto(expression,
								expressionDTO);
						expressionDtos.add(expressionDTO);
					}
				}

				customFilterDTO.setExpressions(expressionDtos);
				list.add(customFilterDTO);
			}
		}

		return list;
	}

	/**
	 * 根据过滤器ID查找表达式
	 * 
	 * @param filterId
	 * @return List<CustomExpressionDTO>
	 */
	@Transactional
	public List<CustomExpressionDTO> findExpressionsByFilterId(Long filterId) {
		List<CustomExpressionDTO> expressionDtos = new ArrayList<CustomExpressionDTO>();
		CustomFilter entity = filterDAO.findById(filterId);
		if (entity.getExpressions() != null) {
			for (CustomExpression expression : entity.getExpressions()) {
				CustomExpressionDTO expressionDTO = new CustomExpressionDTO();
				CustomExpressionDTO.entity2dto(expression, expressionDTO);
				expressionDtos.add(expressionDTO);
			}
		}
		return expressionDtos;
	}

	/**
	 * 添加过滤器
	 * 
	 * @param dto
	 * @param orgs
	 */
	@Transactional
	public void save(CustomFilterDTO dto, String orgs) {
		CustomFilter entity = new CustomFilter();
		CustomFilterDTO.dto2entity(dto, entity);

		if (dto.getUserName() != null) {
			entity.setCreator(dto.getUserName());
			User user = userDAO.findUniqueBy("loginName", dto.getUserName());
			entity.setFilterOwner(user);
		}

		if (StringUtils.hasText(orgs)) {
			entity.setShareGroups(setShareGroups(orgs));
		}

		if (dto.getExpressions() != null && dto.getExpressions().size() > 0) {
			List<CustomExpression> expressions = new ArrayList<CustomExpression>();
			// 添加表达式
			for (CustomExpressionDTO expressionDTO : dto.getExpressions()) {
				CustomExpression expression = new CustomExpression();
				CustomExpressionDTO.dto2entity(expressionDTO, expression);
				expressions.add(expression);
			}

			entity.setExpressions(expressions);
		}

		filterDAO.save(entity);
		dto.setFilterId(entity.getFilterId());

	}
	/**
	 * 根据机构编号查询机构信息
	 * @param orgNos 机构编号组成的字符串，逗号间隔
	 * @return List<Organization>
	 */
	private List<Organization> setShareGroups(String orgNos) {
		String[] ids = orgNos.split(",");
		Long[] groupIds = new Long[ids.length];
		for (int i = 0; i < ids.length; i++) {
			if (StringUtils.hasText(ids[i].trim())) {
				groupIds[i] = Long.valueOf(ids[i].trim());
			}
		}
		List<Organization> organizations = organizationDAO
				.findOrganizationsByIds(groupIds);
/*		List<Organization> subList=new ArrayList<Organization>();//保存所有子节点
		if(organizations!=null && organizations.size()>0){
			for (Organization org:organizations) {
				List<Long> listId = organizationDAO.findOrgChildsIdsByPath(org.getPath());
				Long[] orgIds=(Long[])listId.toArray(new Long[listId.size()]);
				List<Organization> list =organizationDAO.findOrganizationsByIds(orgIds);
				if(list!=null && list.size()>0){
					subList.addAll(list);
				}
			}
		}*/
		return organizations;
	}

	/**
	 * 更新过滤器
	 * 
	 * @param dto
	 * @param orgs
	 */
	@Transactional
	public void update(CustomFilterDTO dto, String orgs) {
		CustomFilter entity = filterDAO.findById(dto.getFilterId());
		entity.setFilterName(dto.getFilterName());
		entity.setFilterDesc(dto.getFilterDesc());
		entity.setShare(dto.getShare());

		if (StringUtils.hasText(orgs)) {
			entity.setShareGroups(setShareGroups(orgs));
		}

		if (entity.getExpressions() == null
				|| entity.getExpressions().size() == 0) {
			List<CustomExpression> expressions = new ArrayList<CustomExpression>();
			entity.setExpressions(expressions);
		} else {
			// 删除原来表达式
			Long[] ids = new Long[entity.getExpressions().size()];
			int i = 0;
			for (CustomExpression expression : entity.getExpressions()) {
				ids[i] = expression.getExpId();
				i++;
			}
			expressionDAO.deleteByIds(ids);

			entity.getExpressions().clear();// 清除表达式
		}

		if (dto.getExpressions() != null) {
			// 重新添加表达式
			for (CustomExpressionDTO expressionDTO : dto.getExpressions()) {
				CustomExpression expression = new CustomExpression();
				CustomExpressionDTO.dto2entity(expressionDTO, expression);
				entity.getExpressions().add(expression);
				// 保存新的表达式
				expression.setCustomFilter(entity);
				expressionDAO.save(expression);
			}
		}
		filterDAO.merge(entity);
	}

	/**
	 * 删除过滤器
	 * 
	 * @param ids 过滤器数组
	 */
	@Transactional
	public void delete(Long[] ids) {

		try {

			filterDAO.deleteByIds(ids);

		} catch (Exception ex) {
			throw new ApplicationException("ERROR_DATA_CAN_NOT_DELETE", ex);
		}
	}

	/**
	 * 根据过滤器ID获取过滤器信息
	 * 
	 * @param filterId
	 */
	@Transactional
	public CustomFilterDTO findById(Long filterId) {
		CustomFilterDTO dto = new CustomFilterDTO();
		CustomFilter entity = filterDAO.findById(filterId);
		if (entity != null && entity.getShareGroups() != null
				&& entity.getShareGroups().size() > 0) {
			Long[] groupIds = new Long[entity.getShareGroups().size()];
			for (int i = 0; i < entity.getShareGroups().size(); i++) {
				groupIds[i] = entity.getShareGroups().get(i).getOrgNo();
			}
			dto.setShareGroupIds(groupIds);
		}
		CustomFilterDTO.entity2dto(entity, dto);
		List<CustomExpressionDTO> expressionDtos = new ArrayList<CustomExpressionDTO>();
		if (entity != null && entity.getExpressions() != null
				&& entity.getExpressions().size() > 0) {
			for (CustomExpression expression : entity.getExpressions()) {
				CustomExpressionDTO expressionDTO = new CustomExpressionDTO();
				CustomExpressionDTO.entity2dto(expression, expressionDTO);
				expressionDtos.add(expressionDTO);
			}
		}

		dto.setExpressions(expressionDtos);

		return dto;

	}

	/**
	 * 根据过滤器查询数据
	 */
	@Transactional
	public PageDTO findPageByFilter(Long filterId, Long[] companyNos,Long[] categorys,
			int start, int limit, String sidx, String sord) {

		CustomFilter filter = filterDAO.findById(filterId);

		if (filter == null) {
			throw new ApplicationException("ERROR_FILTER_NOT_EXISTS");
		} else {
			return filterDAO.findPageByCustomFilter(filter, companyNos,categorys, start,
					limit, sidx, sord);
		}

	}
	
	/**
	 * 根据过滤器查询数据
	 */
	@SuppressWarnings("rawtypes")
    @Transactional
	private List findByCustomFilter(Long filterId, Long[] companyNos,Long[] categorys,
			int start, int limit, String sidx, String sord) {

		CustomFilter filter = filterDAO.findById(filterId);

		if (filter == null) {
			throw new ApplicationException("ERROR_FILTER_NOT_EXISTS");
		} else {
			return filterDAO.findByCustomFilter(filter, companyNos,categorys, start,
					limit, sidx, sord);
		}

	}
	/**
	 * 根据服务机构查找SLA
	 * 
	 * @return String
	 */
	@Transactional
	public PageDTO findShareGroups(Long filterId) {
		PageDTO page = new PageDTO();
		page.setPage(1);
		page.setRows(1000);
		if (filterId != null && filterId != 0) {
			CustomFilter filter = filterDAO.findById(filterId);
			List<Organization> organizations = filter.getShareGroups();
			if (organizations != null && organizations.size() > 0) {
				List<OrganizationDTO> dtos = new ArrayList<OrganizationDTO>(
						organizations.size());
				for (Organization org : organizations) {
					OrganizationDTO orgDTO = new OrganizationDTO();
					orgDTO.setOrgNo(org.getOrgNo());
					orgDTO.setOrgName(org.getOrgName());
					dtos.add(orgDTO);
				}
				page.setData(dtos);
			} else {
				page.setData(null);
			}
		} else {
			page.setData(null);
		}
		return page;
	}
	
	@Transactional
	public void importNewRequestFilter(){
		try {
			LanguageContent lc = LanguageContent.getInstance();
			CustomFilterDTO dto = new CustomFilterDTO();
			dto.setEntityClass("com.wstuo.itsm.request.entity.Request");
			dto.setFilterCategory("request");
			dto.setFilterName("【"+lc.getContent("title.mainTab.request")+"】"+lc.getContent("title.mainTab.request")+lc.getContent("title.newCreate"));
			dto.setShare("share");
			dto.setUserName("admin");
			
			List<CustomExpressionDTO> ex=new ArrayList<CustomExpressionDTO>();
			CustomExpressionDTO exdto=new CustomExpressionDTO();
			exdto.setExpId(1l);
			exdto.setDisplayOperator("label_sla_eq");
			exdto.setJoinType("or");
			exdto.setPropDisplayName("common_state");
			exdto.setOperator("=");
			exdto.setPropDisplayValue(lc.getContent("title.mainTab.request")+lc.getContent("title.newCreate"));
			exdto.setPropName("status.dcode");
			exdto.setPropType("Long");
			DataDictionaryItems ddi = dataDictionaryItemDAO.findUniqueBy("dno", "request_new");
			if(ddi!=null){
				exdto.setPropValue(ddi.getDcode().toString());
			}
			ex.add(exdto);
			
			dto.setExpressions(ex);
			
			expressionService.batchSave(ex);
			// 保存过滤器
			save(dto, "");
	
		} catch (Exception e1) {
			LOGGER.error(e1);
		}
	}
	/**
	 * 默认面板加载基础数据
	 */
	@Transactional
	public Long importFilter(){
		
		try {
			LanguageContent lc = LanguageContent.getInstance();
			CustomFilterDTO dto = new CustomFilterDTO();
			dto.setEntityClass("com.wstuo.itsm.request.entity.Request");
			dto.setFilterCategory("request");
			dto.setFilterName("【"+lc.getContent("title.mainTab.request")+"】"+lc.getContent("FCR.Processing"));
			dto.setShare("share");
			dto.setUserName("admin");
			
			List<CustomExpressionDTO> ex=new ArrayList<CustomExpressionDTO>();
			CustomExpressionDTO exdto=new CustomExpressionDTO();
			exdto.setExpId(1l);
			exdto.setDisplayOperator("label_sla_eq");
			exdto.setJoinType("or");
			exdto.setPropDisplayName("common_state");
			exdto.setOperator("=");
			exdto.setPropDisplayValue(lc.getContent("FCR.Processing"));
			exdto.setPropName("status.dcode");
			exdto.setPropType("Long");
			DataDictionaryItems ddi = dataDictionaryItemDAO.findUniqueBy("dno", "request_one");
			if(ddi!=null){
				exdto.setPropValue(ddi.getDcode().toString());
			}
			ex.add(exdto);
			
			dto.setExpressions(ex);
			
			expressionService.batchSave(ex);
			// 保存过滤器
			save(dto, "");
	
			return dto.getFilterId();
		} catch (Exception e1) {
			LOGGER.error(e1);
		}
		return null;
	}

	public Long getFilterViewId() {
		Long id = null;
		List<CustomFilter> list = filterDAO.findAll();
		if(list !=null && list.size()>0){
			id = list.get(0).getFilterId();
		}
		return id;
	}
}
